﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SysFrame.BP;

namespace AppServer
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDistributedMemoryCache();//启用session之前必须先添加内存
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddSession(options =>
            {
                options.Cookie.Name = ".AdventureWorks.Session";
                options.IdleTimeout = TimeSpan.FromSeconds(10);//设置session的过期时间
                options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
            }
            );
            services.AddResponseCompression(options =>
            {
                options.Providers.Add<GzipCompressionProvider>();
                options.MimeTypes = MimeTypes;
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            //app.UseStaticFiles();
            var mimeTypeProvider = new FileExtensionContentTypeProvider();

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    var headers = context.Context.Response.Headers;
                    var contentType = headers["Content-Type"];

                    if (contentType != "application/x-gzip" && !context.File.Name.EndsWith(".gz"))
                    {
                        return;
                    }

                    var fileNameToTry = context.File.Name.Substring(0, context.File.Name.Length - 3);

                    if (mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType))
                    {
                        headers.Add("Content-Encoding", "gzip");
                        headers["Content-Type"] = mimeType;
                    }
                }
            });
            app.UseResponseCompression();
            app.UseCookiePolicy();


            app.UseCors(builder => {
                builder.WithOrigins("http://localhost:7070", "http://shixixiyue.gitee.io");
                //builder.AllowAnyOrigin();
                builder.AllowAnyHeader();
                builder.AllowAnyMethod();
                builder.AllowCredentials();
            });
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            DbHelperMySQL.SetConnectionString(GetConnectionString());
        }

        public static readonly IEnumerable<string> MimeTypes = new[]
        {
            // General
            "text/plain",
            // Static files
            "text/css",
            "application/javascript",
            // MVC
            "text/html",
            "application/xml",
            "text/xml",
            "application/json",
            "text/json",
        };

        /// <summary>
        /// 数据库类型
        /// </summary>
        public static string SQLTYPE { get; set; }

        /// <summary>
        /// 得到数据路径
        /// </summary>
        /// <returns></returns>
        public string GetConnectionString()
        {
            SQLTYPE = Configuration["DataConfig:SQLTYPE"];
            string server = Configuration["DataConfig:SQLServer:SERVER"];
            string database = Configuration["DataConfig:SQLServer:DATABASE"];
            string uid = Configuration["DataConfig:SQLServer:USER"];
            string pwd = Configuration["DataConfig:SQLServer:PASSWORD"];
            string config = "server=" + server + ";database=" + database + ";uid=" + uid + ";pwd=" + pwd + "";
            if (SQLTYPE == "2")
            {
                server = Configuration["DataConfig:MySQL:SERVER"];
                database = Configuration["DataConfig:MySQL:DATABASE"];
                uid = Configuration["DataConfig:MySQL:USER"];
                pwd = Configuration["DataConfig:MySQL:PASSWORD"];
                config = "server=" + server + ";database=" + database + ";user id=" + uid + ";password=" + pwd + ";Charset=gbk";
            }
            return config;
        }
    }
}
